<?php
/* *
 * 功能：支付宝服务器异步通知页面
 * 版本：3.3
 * 日期：2012-07-23
 * 说明：
 */

require_once("/var/www/html/new/com.inc.php");
require_once("/var/www/html/new/d/class/OrderRecord.php");
require_once("/var/www/html/new/d/shops/alipay/lib/alipay_notify.class.php");
// require_once("/var/www/html/new/conf/yd.le.je");
if($_POST['trade_status'] == 'TRADE_SUCCESS'){// 支付成功以后找到分销商 ID

    $ac=$GLOBALS['_ac'];
    $pw=$GLOBALS['_pw'];
    $s = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));
    
    $orderid = $_POST['out_trade_no']; // 平台订单号
    
    // 合并订单去除前缀
    if(substr($orderid,0,2)=='st') $orderid = substr($orderid,0,2);
    
    $or=new OrderRecord($orderid,$s);
    // $orders=$or->info();

    $xml = $s->Order_Globle_Search("","","","","","","","","","","","",$orderid,"","","","","",1,1,0,1,"","","","","","","","","",0,1);
	$simxml = simplexml_load_string($xml);
	$mid = (int)$simxml->Rec->UUmid;
	
	$orders=$or->info_n($mid);
	$aid = (int)$orders['mainOrder']->UUaid;
    $mid = (int)$orders['mainOrder']->UUmid;
	
	 // 防止由于网络延迟支付宝重复调用
    if((string)$orders['mainOrder']->UUpaystatus==1) exit("success");
    
	
    // 引入支付宝配置文件
    // define('BUYER',$mid);
    define('BUYER',$aid);
    require_once("/var/www/html/alipay/alipay.config.world.php");
    
    // 支付到票付通
    $alipay_to_pft = false;
    if($alipay_config['seller_email']=='pft12301@126.com'){
        $alipay_to_pft = true;
    }
    
}

//计算得出通知验证结果
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyNotify();

if($verify_result) {//验证成功
	
	$out_trade_no = $_POST['out_trade_no'];// 平台订单号
	$trade_no = $_POST['trade_no'];        // 支付宝交易号
	$trade_status = $_POST['trade_status'];// 交易状态

    if($_POST['trade_status'] == 'TRADE_FINISHED') {
    
        logResult("1:$trade_no:$out_trade_no:$trade_status\n");
        
    }elseif($_POST['trade_status'] == 'TRADE_SUCCESS') {	
    
        if(substr($out_trade_no,0,2)=='st'){// 多个订单合在一起
            // $ydle=new yd_go_sql();
            // $ydle->connect();
            $sql="SELECT old FROM uu_unitpay WHERE new='$out_trade_no' AND status=0 LIMIT 1";
            $GLOBALS['le']->query($sql);
            $GLOBALS['le']->fetch_assoc();
            $subOrders = $GLOBALS['le']->f('old');
            $subOrders = explode(',', $subOrders);
          
            foreach($subOrders as $subOrdernum){
            
                $or=new OrderRecord($subOrdernum,$s);
                $orders=$or->info();

                $aid = (string)$orders['mainOrder']->UUaid;
                $mid = (string)$orders['mainOrder']->UUmid;
                
                $total_fee = total_fee($orders);// 获取总价格
            
                // 分润
                $aid_money = fenRun($s,$subOrdernum,$total_fee,$orders,$alipay_to_pft);
                
                // 平台支付宝交易记录变更已支付
                $str="update pft_alipay_rec set status=1,dtime=now(),`trade_no`='$trade_no' where out_trade_no='$subOrdernum' limit 1";
                $GLOBALS['le']->query($str);
                
                $result = $s->Mod_Order_Status($subOrdernum,1);
                write_logs("[$subOrdernum]订单状态修改:$result",'success_logs_debug.txt');
                $s->reSend_SMS_Global_PL($subOrdernum,$aid,$mid);//最后重发短信
            }
            
            $sql="UPDATE uu_unitpay SET status=1 WHERE new='$out_trade_no' AND status=0 LIMIT 1";
            // $ydle->query($sql);
            
        }else{
            
            // 获取总价格并插入 pft_member_alipay
            $total_fee = total_fee($orders, $alipay_to_pft);
        
            // 分润
            fenRun($s,$out_trade_no,$total_fee,$orders,$alipay_to_pft);
            
            // 平台支付宝交易记录变更已支付
            $str="update pft_alipay_rec set status=1,dtime=now(),`trade_no`='$trade_no' where out_trade_no='$out_trade_no' limit 1";
            $GLOBALS['le']->query($str);

            $result = $s->Mod_Order_Status($out_trade_no,1);
            // 支付后交互
			$tid = (int)$orders['mainOrder']->UUtid;
			$sql = "select Mpath,Mdetails from uu_jq_ticket where id=$tid limit 1";
			$GLOBALS['le']->query($sql);
			$GLOBALS['le']->fetch_assoc();
			if(($Mpath=$GLOBALS['le']->f('Mpath'))){
				
				$relation_info_req = http_build_query(array(
                    'Action'  => 'Relation_after_pay',
                    'Ordern'  => $out_trade_no,
                    'Fid'     => (int)$orders['mainOrder']->UUmid,
                ));
                file_get_contents($Mpath.'?'.$relation_info_req);
			}
			
			write_logs("[$out_trade_no]订单状态修改:$result",'success_logs_debug.txt');
			
			include '/var/www/html/new/d/class/OrderSmsManual.class.php';
            $smsManual  = new \PFT\SMS\OrderSmsManual($s);
            $ret = $smsManual->SendByOrderInfo($orders);
            if ($ret!=100) {
                write_logs("短信发送失败|订单号[$out_trade_no]|错误代码[$ret]", 'success_logs_1.log');
            }
            // $s->reSend_SMS_Global_PL($out_trade_no,$aid,$mid);//最后重发短信
            
        }
	}

        
	echo "success";		//请不要修改或删除
	// logResult("2:$trade_no:$out_trade_no:$trade_status\n");
}
else {
    
    echo "fail";// 验证失败
	err(date('Y-m-d H:i:s')."------3:$trade_no:$out_trade_no:$trade_status\n");
}


// 转分销分润
function fenRun($s,$ordern,$total_fee,$orders,$to_pft){
    
    $aid = (string)$orders['mainOrder']->UUaid;
    $mid = (string)$orders['mainOrder']->UUmid;
    
    $add = 0; $cut = 1;
    // 非自供产品获取结算价
    if($aid!=$mid){
        $total_money = 0;
        $pid = (string)$orders['mainOrder']->UUpid;// 产品 id
        $begintime = (string)$orders['mainOrder']->UUbegintime;// 游玩时间价格
        $account = (string)$orders['mainOrder']->UUfromt;// 游玩时间价格
        $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
        if($ret==105||$ret==1065){
            $total_money = $total_fee;
        }else{
            $obj = simplexml_load_string($ret);
            $total_money = (string)$obj->Rec->UUsprice * (int)$orders['mainOrder']->UUtnum;
        }
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $pid = (string)$child->UUpid;// 产品 id
                $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
                if($ret!=105 && $ret!=1065){
                    $obj = simplexml_load_string($ret);
                    $total_money += (string)$obj->Rec->UUsprice * (int)$child->UUtnum;
                }
            }
        }
    }
    
    if($to_pft){// 支付给了票付通，最下级供应商加钱
		// 2015/03/08 财务需求，林农过审核，提交光鹏，abc处理
		// $s->PFT_Member_Fund_Modify(1, 0, $total_fee, $cut, 0,null,0, 0,$ordern);
		
        $s->PFT_Member_Fund_Modify($aid, 0, $total_fee, $add, 0,null,0, 1,$ordern);
    }


    // 产品多级销售分润
    $str="select aids_money from uu_order_fx_details where orderid='$ordern' limit 1";
    $GLOBALS['le']->query($str);
    $lirun = $GLOBALS['le']->fetch_assoc();
    if ($lirun['aids_money']){

        // 子票没有记录分润，获取子票价格
        $childMenoy = array();
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $aids = explode(',',(string)$child->UUaids);
                krsort($aids);
                $aids_price = explode(',',(string)$child->UUaids_price);
                krsort($aids_price);
                foreach($aids as $k=>$et){
                    if($k==0) break;// 最后一个不用操作了
                    $childMenoy[$et]+= $aids_price[$k-1] * (string)$child->UUtnum;
                }
            }
        }
        // 主订单的 aids
        $main_aids = explode(',',(string)$orders['mainOrder']->UUaids);
        $aids_money = unserialize($lirun['aids_money']);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
            $action = ($row[2]==0) ? $cut : $add;//0减少,1增加和接口相反
            $Mmoney=$row[3];
            if($action==0){ // 加钱
                $ks = array_search($fid,$main_aids);
                $ks = $ks+1;
                $Mmoney += isset($childMenoy[$main_aids[$ks]]) ? $childMenoy[$main_aids[$ks]]:0;
            }else{
                $Mmoney += isset($childMenoy[$fid]) ? $childMenoy[$fid]:0;
            }

            if($row[1]==0){//信用额度
                $dmode = 1;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,$row[4],0,2,$ordern);
            }else{//资金
                $dmode = 0;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,NULL,0,0,$ordern);
            }
        }
    }
    return $total_money;// 返回上级利润
}

// 获取订单总价格，以分为单位
function total_fee($orders, $to_pft=false){

    $total_fee = 0;
    $aid = (string)$orders['mainOrder']->UUaid;
    $mid = (string)$orders['mainOrder']->UUmid;
    $total_fee=((string)$orders['mainOrder']->UUtprice * (string)$orders['mainOrder']->UUtnum);
    $ordernum = (string)$orders['mainOrder']->UUordernum;
    $str="insert pft_member_alipay set fid=$mid,orderid='$ordernum',total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),dtype=0,daction=1";
    $GLOBALS['le']->query($str);
	if($to_pft){ // 2015/03/08 财务需求，林农过审核，提交光鹏，abc处理
		$str="insert pft_member_alipay set fid=1,orderid='$ordernum',total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),dtype=0";
		$GLOBALS['le']->query($str);
	}
    // 加上非套票的子票价格
    if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
        foreach($orders['childOrder'] as $key=>$child){
            $tmp = ((string)$child->UUtprice * (string)$child->UUtnum);
            $total_fee+=$tmp;
            $ordernum = (string)$child->UUordernum;
            $str="insert pft_member_alipay set fid=$mid,orderid='$ordernum',total_fee='$tmp',money='$tmp',ali_account='',rectime=now(),dtype=0,daction=1";
            $GLOBALS['le']->query($str);
			if($to_pft){
				$str="insert pft_member_alipay set fid=1,orderid='$ordernum',total_fee='$tmp',money='$tmp',ali_account='',rectime=now(),dtype=0";
				$GLOBALS['le']->query($str);
			}
        }
    }
    return $total_fee;
}

function write_logs($txt,$file="success_logs_debug.txt"){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function err($txt){
	$fp = fopen("debug.txt","a");
	flock($fp, LOCK_EX) ;
	fwrite($fp,$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}
?>